const db = require('../db');
const bcrypt = require('bcryptjs');

exports.getUserInfo = (req, res) => {
  // res.send('get ok');
  const sql =
    'select id, username, nickname, email, user_pic from ev_users where id=?';

  db.query(sql, req.user.id, (err, result) => {
    if (err) {
      res.cc(err.message);
      return;
    }

    if (result.length !== 1) {
      res.cc('查询失败');
      return;
    }

    res.send({
      status: 0,
      message: '查询成功',
      data: result[0],
    });
  });
};

exports.updateUserInfo = (req, res) => {
  const { id } = req.body;
  const sql = 'update ev_users set ? where id=?';

  db.query(sql, [req.body, id], (err, result) => {
    if (err) {
      return res.cc(err);
    }

    if (result.affectedRows !== 1) {
      res.cc('更新失败');
      return;
    }
    res.send({
      status: 0,
      message: '更新成功',
    });
  });
  // res.send('update okk');
};

exports.updatePassword = (req, res) => {
  const sql = 'select * from ev_users where id=?';

  db.query(sql, req.user.id, (err, result) => {
    if (err) return res.cc(err);

    if (result.length !== 1) {
      res.cc('更新失败');
      return;
    }

    // req.body.oldPwd result[0].password
    const compareResult = bcrypt.compareSync(
      req.body.oldPwd,
      result[0].password
    );
    if (!compareResult) return res.cc('旧密码不一致');

    // newPwd
    const sql = 'update ev_users set password=? where id=?';
    const newPwd = bcrypt.hashSync(req.body.newPwd);

    db.query(sql, [newPwd, req.user.id], (err, result) => {
      if (err) return res.cc(err);

      if (result.affectedRows !== 1) return res.cc('更新失败');

      res.send({
        status: 0,
        message: '更新成功',
      });
    });
  });
};

exports.updateAvatar = (req, res) => {
  const sql = 'update ev_users set user_pic=? where id=?';
  db.query(sql, [req.body.avatar, req.user.id], (err, result) => {
    if (err) {
      return res.cc(err);
    }

    if (result.affectedRows !== 1) {
      return res.cc('更新头像失败');
    }

    res.send({
      status: 0,
      message: '更新头像成功',
    });
  });
};
